package multidraw.model.server;

import java.rmi.RemoteException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import multidraw.model.Canvas;
import multidraw.model.Shape;
import multidraw.model.TextBox;
import multidraw.model.commands.Command;

/**
 * This class stores the information a session.
 * @author cuongbk
 *
 */
public class SessionInfo implements Canvas {
	public String sessionID;
	public Hashtable<String, Role> userRoles = new Hashtable<String, Role>();
	public CoreData coreData = new CoreData();
	protected CanvasServer canvasServer;
	
	public SessionInfo(String sessionID, CanvasServer server) {
		this.sessionID = sessionID;
		this.canvasServer = server;
	}

	@Override
	public void applyAddShape(Shape s) {
		// TODO Auto-generated method stub
		coreData.shapes.add(s);
	}

	@Override
	public void applyCommandToCoreData(Command c) {
		// TODO Auto-generated method stub
		coreData.revisionID++;
		c.setCanvas(this);
		c.execute();
	}

	@Override
	public long getNextID() {
		long id = 1;
				
		for (Shape s: coreData.shapes) {
			if (id < s.getShapeID()) id = s.getShapeID();
		}
		
		return id + 1;
	}

	@Override
	public void applyAddChar(long shapeID, char ch) {
		// TODO Auto-generated method stub
		for (Shape s: coreData.shapes) {
			if (s.getShapeID() == shapeID) {
				TextBox t = (TextBox) s;
				t.addChar(ch);
				return;
			}
		}
	}

	@Override
	public List<Shape> getShapes() {
		// TODO Auto-generated method stub
		return coreData.shapes;
	}

	@Override
	public void setSelectedObjectIndex(int index) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void applyAddUser(String name) {
		// TODO Auto-generated method stub
		
	}
	
	public void applyCommand(Command command) {
		// TODO Auto-generated method stub
		//command
		applyCommandToCoreData(command);
		
		//send it to other clients
		Enumeration<String> enu =  userRoles.keys();
		
		while (enu.hasMoreElements()) {
			String o = enu.nextElement();
			ClientInfo clientInfo = canvasServer.getClientInfo(o);
			if (clientInfo != null)
				clientInfo.updates.add(command);			
		}
		
		notifyObservers();
	}
	
	public void notifyObservers() {
		//send it to other clients
		Enumeration<String> enu =  userRoles.keys();
		
		while (enu.hasMoreElements()) {
			String o = enu.nextElement();
			ClientInfo clientInfo = canvasServer.getClientInfo(o);
			if (clientInfo != null) {
				try {
					clientInfo.clientObject.updateModelContent();
				} catch (RemoteException re) {
					System.out.println(re);
				}
			}
		}
	}
	
	public boolean joinClient(String clientID) {
		userRoles.put(clientID, Role.COLLABORATOR);
		notifyObservers();
		return true;
	}
}
